<script setup>
import PostList from '../components/PostList.vue'
import FilterBar from '../components/FilterBar/FilterBar.vue'
import { useLastPostListQuery } from '@/composables/usePostDataQuery'
import { useGlobalStore } from '@/stores/globalStore'
import ContainerSplitOrFull from '@/components/commonUI/ContainerSplitOrFull.vue'
const globalStore = useGlobalStore()

const viewMode = ref((localStorage.getItem('viewMode') || 'list') === 'list' ? 0 : 1)

const postFilter = computed(() => globalStore.postFilter)


const { data, fetchNextPage, hasNextPage, isFetching, isLoading } = useLastPostListQuery(postFilter)
const flatData = computed(() => {
  return data.value?.pages.flatMap((page) => page.result.data) || []
})

const loadMore = () => {
  if (isFetching.value) return
  fetchNextPage()
}

const handleFilterChange = (filterNum) => {
  globalStore.setPostFilter(filterNum)
}

const handleViewModeChange = (viewModeNum) => {
  viewMode.value = viewModeNum
  globalStore.setViewMode(viewModeNum ? 'gallery' : 'list')
}
</script>

<template>
  <ContainerSplitOrFull>
    <div
      v-infinite-scroll="loadMore"
      :infinite-scroll-disabled="isFetching || !hasNextPage"
      :infinite-scroll-distance="5"
      class="p-3 max-w-[1600px] mx-auto">
      <div class="mb-2 flex gap-4">
        <FilterBar
          :filter="globalStore.postFilter"
          @change="handleFilterChange"
          :checked-title="['最新', '活跃']"
          :menu-options="['发帖日期', '最近活跃']"  
          title="排序" />
        <FilterBar
          :filter="viewMode"
          @change="handleViewModeChange"
          :checked-title="['列表', '图库']"
          :menu-options="['列表', '图库']"
          title="浏览模式" />
      </div>

      <PostList :posts-data="flatData" />

      <div v-if="isLoading" class="p-14 text-center text-sm text-[--text-2]">加载中...</div>
      <div v-if="!isLoading && !hasNextPage" class="p-14 text-center text-sm text-[--text-2]">没有更多了</div>
    </div>
  </ContainerSplitOrFull>
</template>

<style scoped lang="scss"></style>
